package com.reone.jsbridgedemo.webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.github.lzyzsd.jsbridge.BridgeHelper;
import com.github.lzyzsd.jsbridge.IWebView;
import com.reone.jsbridgedemo.client.JSBridgeChromeClient;
import com.reone.jsbridgedemo.client.JSBridgeClient;
import com.reone.jsbridgedemo.utils.NativeMethodList;


/**
 * Created by wangxingsheng on 2018/7/13.
 */
public class JSBridgeWebView extends WebView implements IWebView {
    private BridgeHelper bridgeHelper;

    public JSBridgeWebView(Context context) {
        super(context);
        init();
    }

    public JSBridgeWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public JSBridgeWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        bridgeHelper = new BridgeHelper(this);
        initSettings(getSettings());
        initListener();
        initJsMethodModel();
    }

    public BridgeHelper getBridge() {
        return bridgeHelper;
    }

    private void initJsMethodModel() {
        addJavascriptInterface(new NativeMethodList(), "nativeMethod");
    }

    private void initListener() {
        setWebViewClient(new JSBridgeClient(bridgeHelper));
        setWebChromeClient(new JSBridgeChromeClient());
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initSettings(WebSettings settings) {
        settings.setJavaScriptEnabled(true);
    }

}
